const dataBase = require('../../mysql')

const sql = require('../../mysql/sql')
const verify = require('../../auth/verify')
const verifyRequestMethod = require('../../tool/verifyRequestMethod')
const md5 = require('md5')
/**
 * @description 修改密码
 */
module.exports = function () {
  const that = this
  const authorization = this.request.headers.authorization
  const query = this.getQueryData(this.request.url)
  /**
   * @description 请求验证
   */
  verifyRequestMethod(this.request, 'GET').then(function () {
    /**
     * @description 授权验证
     */
    if (that.isDef(authorization)) {
      return verify(authorization)
    } else {
      return Promise.reject(new Error('缺少Authorization！'))
    }
  }).then(function (data) {
    /**
     * @description 用户名
     * @type {string|string}
     */
    const password = query.password
    if (!password) {
      that.response.outPrintError('密码不能为空，请输入密码！')
    } else if (!/^(?=.*\d)(?=.*[a-zA-Z]).{6,20}$/.test(password)) {
      that.response.outPrintError('密码至少6个字符最多20个字符，至少1个大写字母或1个小写字母，和1个数字！')
    } else{
      return dataBase.connect(sql.SQL_UPDATE_USER_PASSWORD(data.username, md5(password)))
    }
  }).then(function (options) {
      that.response.outPrintData({}, '修改成功！')
  }).then(function () {
    that.response.outPrintData({}, '修改成功！')
  }).catch(function (e) {
    that.response.outPrintError((e && e.message) || '未知错误！')
  })
}